import { create } from 'zustand';
import { User } from '@/types';
import { userApi } from '@/services/api';

interface AuthState {
  user: User | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  error: string | null;
  login: () => Promise<void>;
  logout: () => void;
  handleCallback: (code: string) => Promise<void>;
  fetchUser: () => Promise<void>;
}

export const useAuthStore = create<AuthState>((set, get) => ({
  user: null,
  isAuthenticated: false,
  isLoading: false,
  error: null,

  login: async () => {
    set({ isLoading: true, error: null });
    try {
      const loginUrl = await userApi.getLoginUrl();
      console.log('loginUrl:', loginUrl);

      window.location.href = loginUrl;
    } catch (error: any) {
      set({ error: error.message || '登录失败' });
    } finally {
      set({ isLoading: false });
    }
  },

  logout: () => {
    localStorage.removeItem('accessToken');
    localStorage.removeItem('refreshToken');
    set({ user: null, isAuthenticated: false });
  },

  handleCallback: async (code: string) => {
    set({ isLoading: true, error: null });
    try {
      const user = await userApi.handleCallback(code);
      localStorage.setItem('accessToken', user.accessToken);
      if (user.refreshToken) {
        localStorage.setItem('refreshToken', user.refreshToken);
      }
      set({ user, isAuthenticated: true });
    } catch (error: any) {
      set({ error: error.message || '授权回调处理失败' });
    } finally {
      set({ isLoading: false });
    }
  },

  fetchUser: async () => {
    const token = localStorage.getItem('accessToken');
    if (!token) return;

    set({ isLoading: true, error: null });
    try {
      const user = await userApi.getCurrentUser();
      set({ user, isAuthenticated: true });
    } catch (error: any) {
      set({ error: error.message || '获取用户信息失败' });
      // 如果获取用户信息失败，可能是token过期，清除登录状态
      if (error.response?.status === 401) {
        get().logout();
      }
    } finally {
      set({ isLoading: false });
    }
  },
}));